package com.kaoqin.controller;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.kaoqin.code.util.AuthorUtils;
import com.kaoqin.model.Project;
import com.kaoqin.model.Sign;
import com.kaoqin.model.SignLog;
import com.kaoqin.model.SignLogVO;
import com.kaoqin.service.ProjectService;
import com.kaoqin.service.SignLogService;
import com.kaoqin.service.SignService;
import com.kaoqin.util.ArrayUtils;
import com.kaoqin.util.DateUtil;
import com.kaoqin.util.ImportExcelUtil;
import com.kaoqin.util.JxlsExcelUtil;
import com.kaoqin.util.SysUtils;

/**
 * @ClassName: EmployeeController
 * @Description: 员工考勤
 * @author: Janus
 * @date: 2017-7-20 下午6:41:37   
 */
@Controller
@RequestMapping("sign")
public class SignController {
	@Autowired
	private SignService signService;
	@Autowired
	private SignLogService signLogService;
	@Autowired
	private ProjectService projectService;
	/*
	 * 首页列表查询
	 */
	@RequestMapping("/list")
	public String signList(HttpServletRequest request, Sign sign, Model model) throws Exception {
		String proCode = getCurrProCode(request);
		String token = AuthorUtils.getToken(request);
		Gson gson = new Gson();
		List<Sign> findAll = signService.findAll(sign);
		List<Project> proList = projectService.findAll(proCode);
		model.addAttribute(sign);
		model.addAttribute("selectJson", gson.toJson(proList));
		model.addAttribute("dataJson", gson.toJson(findAll));
		model.addAttribute("token",token);
		return "/sign/index";
	}
	/**
	 * 上班下班签到
	 */
	@RequestMapping("/signClick")
	@ResponseBody
	public String signClick(String dataId, String dataType, String selectVal) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			SignLog signLog = new SignLog();
			signLog.seteId(Long.parseLong(dataId));
			signLog.setProjectCode(selectVal);
			signLog.setSignDate(DateUtil.getCurrentTimestamp(null, DateUtil.DATE_DEFAULT_FORMAT));
			signLogService.packageSignDetail(signLog, dataType);
			map.put("status", "success");
		} catch (Exception e) {
			map.put("status", "error");
			e.printStackTrace();
		}
		return new Gson().toJson(map);
	}
	/**
     * 查看详细信息
     */
	@RequestMapping("/signDetails")
	public String signDetails(String eId, Model model) {
		Timestamp currentTimestamp = DateUtil.getCurrentTimestamp(null, DateUtil.DATE_DEFAULT_FORMAT);
		SignLog signLog = new SignLog();
		signLog.seteId(Long.parseLong(eId));
		signLog.setSignDate(currentTimestamp);
		signLog.setOrderSql(" order by id desc");
		List<SignLog> findAll = signLogService.findAll(signLog);
		Map<String, String> proMap = projectService.packageCodeAndName();
		Long countShiChang = 0L;
		String projectCode = null;
		String projectName = null;
		for (SignLog slog : findAll) {
			projectCode = slog.getProjectCode();
			projectName = proMap.get(projectCode);
			slog.setProjectName(projectName);
			if (slog.getSignToWork() == null || slog.getSignOffWork() == null) {
				slog.setSignShiChang("0");
				continue;
			}
			Long endTime = slog.getSignOffWork() == null ? 0 : slog.getSignOffWork().getTime();
			Long beginTime = slog.getSignToWork() == null ? 0 : slog.getSignToWork().getTime();
			Long shicha = endTime - beginTime;
			countShiChang += shicha;
			slog.setSignShiChang(DateUtil.formatTime(shicha));
		}
		model.addAttribute("eId", eId);
		Sign sign = new Sign();
		sign.setId(Long.parseLong(eId));
		List<Sign> signList = signService.findAll(sign);
		if (SysUtils.isNotList(signList)) {
			Sign signObj = signList.get(0);
			model.addAttribute("bianhao", "编号:" + signObj.getJobNumber());
			model.addAttribute("xingming", "姓名:" + signObj.getName());
			model.addAttribute("shichang", "当日总时长:" + DateUtil.formatTime(countShiChang));
		}
		model.addAttribute("List", findAll);
		return "sign/detailsModel";
	}
	/**
     * 编辑列表
     */
	@RequestMapping("/editList")
	public String signEditList(HttpServletRequest request, Sign sign, Model model) {
		String proCode = getCurrProCode(request);
		Gson gson = new Gson();
		List<Sign> findAll = signService.findAll(sign);
		List<Project> proList = projectService.findAll(proCode);
		model.addAttribute(sign);
		model.addAttribute("selectJson", gson.toJson(proList));
		model.addAttribute("dataJson", gson.toJson(findAll));
		return "sign/editList";
	}
	/**
     * 编辑列表
     */
	@RequestMapping("/signEdit")
    public String signEdit(HttpServletRequest request,String eId,String signDate,Model model) {
        String proCode = getCurrProCode(request);
        Map<String, String> proMap = projectService.packageCodeAndName();
        Gson gson = new Gson();
        SignLog signLog = new SignLog();
        signLog.seteId(Long.parseLong(eId));
        if(StringUtils.isNotBlank(signDate)){
            Timestamp currentTimestamp = DateUtil.getCurrentTimestamp(DateUtil.getDateFormat(signDate), DateUtil.DATE_DEFAULT_FORMAT);
            signLog.setSignDate(currentTimestamp);
        }
        List<SignLog> findAll = signLogService.findAll(signLog);
        String projectCode=null;
        String projectName=null;
        for (SignLog sl : findAll) {
            projectCode = sl.getProjectCode();
            projectName = proMap.get(projectCode);
            sl.setProjectName(projectName);
            sl.setSignOffWorkStr(DateUtil.timestamp2String(sl.getSignOffWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
            sl.setSignToWorkStr(DateUtil.timestamp2String(sl.getSignToWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
        }
        List<Project> proList = projectService.findAll(proCode);
        Sign sign =new Sign();
        sign.setId(Long.parseLong(eId));
        List<Sign> SignList = signService.findAll(sign);
        if(SysUtils.isNotList(SignList)){
            Sign sign2 = SignList.get(0);
            model.addAttribute("sign",sign2);
        }
        model.addAttribute("eId",eId);
        model.addAttribute("signDate",signDate);
        model.addAttribute("selectJson", gson.toJson(proList));
        model.addAttribute("dataJson1", gson.toJson(findAll));
        return "sign/editList-edit";
    }
	/**
	 * 签到信息编辑
	 */
	@RequestMapping("/editSignLogWin")
	public String editSignLogWin(HttpServletRequest request,String eId,Model model){
	    String proCode = getCurrProCode(request);
        List<Project> proList = projectService.findAll(proCode);
        model.addAttribute("proList", proList);
        SignLog signLog = new SignLog();
        signLog.setId(Long.parseLong(eId));
        List<SignLog> findAll = signLogService.findAll(signLog);
        if(SysUtils.isNotList(findAll)){
            SignLog sl = findAll.get(0);
            Sign sign =new Sign();
            sign.setId(sl.geteId());
            List<Sign> SignList = signService.findAll(sign);
            if(SysUtils.isNotList(SignList)){
                Sign sign2 = SignList.get(0);
                model.addAttribute("sign",sign2);
            }
            Map<String, String> proMap = projectService.packageCodeAndName();
            String projectCode = sl.getProjectCode();
            String projectName = proMap.get(projectCode);
            sl.setProjectName(projectName);
            sl.setSignOffWorkStr(DateUtil.timestamp2String(sl.getSignOffWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
            sl.setSignToWorkStr(DateUtil.timestamp2String(sl.getSignToWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
            model.addAttribute("signLog",sl);
        }
        return "sign/editList-editWin";
	}
	/**
	 * @Title:editSignLogDel 
	 * @Description:删除签到信息
	 * @author yunquan.hao
	 * @Date 2018年4月16日 上午11:37:37
	 */
	@RequestMapping("/editSignLogDel")
	@ResponseBody
	public Map<String,Object> editSignLogDel(HttpServletRequest request,String eId,Model model){
		Map<String,Object> result = new HashMap<>();
		try {
			if(StringUtils.isNotBlank(eId)) {
				signLogService.delSignLog(Integer.parseInt(eId));
				result.put("code","2000");
			}
		} catch (Exception e) {
			result.put("code","4000");
			e.printStackTrace();
		}
        return result;
	}
	/**
     * 更新签到信息
     */
	@RequestMapping("updateSignLog")
	@ResponseBody
	public String updateSignLog(HttpServletRequest request,String id,String projectCode,String signToWorkStr,String signOffWorkStr){
	    Map<String, Object> map = new HashMap<String, Object>();
        try {
        	String stratDate = request.getParameter("signToWorkStr");
        	String endDate = request.getParameter("signOffWorkStr");
            SignLog signLog = new SignLog();
            signLog.setId(Long.parseLong(id));
            signLog.setProjectCode(projectCode);
            if(StringUtils.isNotBlank(stratDate)) {
            	signLog.setSignToWork(DateUtil.getCurrentTimestamp(DateUtil.getDateTimeFormat(stratDate), DateUtil.DATETIME_DEFAULT_FORMAT));
            }
            if(StringUtils.isNotBlank(endDate)) {
        	   signLog.setSignOffWork(DateUtil.getCurrentTimestamp(DateUtil.getDateTimeFormat(endDate), DateUtil.DATETIME_DEFAULT_FORMAT));
            }
            signLogService.updateSignLog(signLog);
            map.put("status", "success");
        } catch (Exception e) {
            map.put("status", "error");
            e.printStackTrace();
        }
        return new Gson().toJson(map);
	}
	/**
	 * 历史信息查询
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/historyList")
	public String historyList(HttpServletRequest request,Model model) throws UnsupportedEncodingException{
		String jobNumber=request.getParameter("jobNumber");
		String name=request.getParameter("name");   
		if(StringUtils.isNotBlank(name)) {
			name = java.net.URLDecoder.decode(name,"UTF-8"); 
		}
		String statDate = request.getParameter("statDate");
		String endDate = request.getParameter("endDate");
		String pageNum = request.getParameter("pageNum");
		int pageN = StringUtils.isBlank(pageNum) ? 1:Integer.parseInt(pageNum);
		SignLogVO signLog = new SignLogVO();
		signLog.setJobNumber(jobNumber);
		signLog.setName(name);
		signLog.setParamStatDate(
				DateUtil.getFormatTimestamp(DateUtil.getDateFormat(statDate), DateUtil.DATE_DEFAULT_FORMAT));
		signLog.setParamEndDate(
				DateUtil.getFormatTimestamp(DateUtil.getDateFormat(endDate), DateUtil.DATE_DEFAULT_FORMAT));
		String proCode = getCurrProCode(request);
		if("()".equals(proCode)){
			proCode=" sl.project_code is not null";	
		}else{
			proCode=" sl.project_code in "+proCode;	
		}
		signLog.setParamProCode(proCode);   
		//signLog.setLimitSql(" limit "+stat+","+end);
		signLog.setPageNum(pageN);
		PageInfo<SignLogVO> page = signLogService.findHistorySignLogList(signLog);
		for (SignLogVO sl : page.getList()) {
            sl.setSignOffWorkStr(DateUtil.timestamp2String(sl.getSignOffWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
            sl.setSignToWorkStr(DateUtil.timestamp2String(sl.getSignToWork(), DateUtil.DATETIME_DEFAULT_FORMAT));
        }
		model.addAttribute("signLogList",page.getList());
		model.addAttribute("signLog", signLog);
		model.addAttribute("statDate", statDate);
		model.addAttribute("endDate", endDate);
		model.addAttribute("Page", page);
		return "sign/historyList";
	}
	/**
	 * 获取当前项目code
	 * @param request
	 * @return
	 */
	private String getCurrProCode(HttpServletRequest request) {
		Object attribute = request.getAttribute("currentIp");
        String proCode = "";
        if (attribute != null) {
            String ip = attribute.toString();
            proCode = signService.findProCodeByIp(ip);
            proCode = "(" + ArrayUtils.arrayToStringSql(proCode.split(",")) + ")";
        }
		return proCode;
	}
	/**
     * 导出excel
     */
	@RequestMapping("/export")
	public void export(HttpServletRequest request, HttpServletResponse response, String statDate, String endDate,
			String proCode) {
		String templateFileName = request.getServletContext().getRealPath("/")
				+ "/template/downloadStatisticsTime.xlsx";
		String destFileName = "签到统计报表.xls";
		List<SignLogVO> signLogList = new ArrayList<SignLogVO>();
		// 查询数据
		SignLog signLog = new SignLog();
		signLog.setParamStatDate(
				DateUtil.getCurrentTimestamp(DateUtil.getDateFormat(statDate), DateUtil.DATE_DEFAULT_FORMAT));
		signLog.setParamEndDate(
				DateUtil.getCurrentTimestamp(DateUtil.getDateFormat(endDate), DateUtil.DATE_DEFAULT_FORMAT));
		if(StringUtils.isNotBlank(proCode)){
			signLog.setParamProCode(proCode);    
		}
		List<String> sheetListName = new ArrayList<String>();
		sheetListName.add("签到数据详情");
		sheetListName.add("签到数据合计");
		signLogList = signLogService.findSignDataToExcel(signLog);
		Map<String, List> beans = new HashMap<String, List>();
		List<SignLogVO> countList = new ArrayList<SignLogVO>();
		packageSignLogCount(signLogList, countList);
		beans.put("signLogList", signLogList);
		beans.put("countList", countList);
		//XLSTransformer transformer = new XLSTransformer();
		InputStream in = null;
		OutputStream out = null;
		// 设置响应
		response.setHeader("Content-Disposition", "attachment;filename=" + SysUtils.encodingFileName(destFileName));
		response.setContentType("application/vnd.ms-excel");
		try {
			in = new BufferedInputStream(new FileInputStream(templateFileName));
			//多sheet页
			Workbook workbook = JxlsExcelUtil.transformMultipleSheetsListByMap(beans, sheetListName, in);
			//单Sheet页
			//Workbook workbook = transformer.transformXLS(in, beans);
			out = response.getOutputStream();
			// 将内容写入输出流并把缓存的内容全部发出去
			workbook.write(out);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}
	 /** 
     * 描述：通过 jquery.form.js 插件提供的ajax方式上传文件 
     * @param request 
     * @param response 
     * @throws Exception 
     */  
    @ResponseBody  
    @RequestMapping(value="/ajaxUpload",method={RequestMethod.GET,RequestMethod.POST})  
    public void ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {  
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
        InputStream in =null;  
        List<List<Object>> listob = null;  
        MultipartFile file = multipartRequest.getFile("upfile");  
        if(file.isEmpty()){  
            throw new Exception("文件不存在！");  
        }  
          
        in = file.getInputStream();  
        listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
          
        //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出  
        
        Sign vo =null;
        List<Sign> signList = new ArrayList<>();
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i);  
            vo = new Sign();  
            vo.setJobNumber(String.valueOf(lo.get(0)).trim());  
            vo.setName(String.valueOf(lo.get(1)).trim());  
            signList.add(vo);
            
        }  
        if(signList.size() > 0) {
        	signService.saveAll(signList);
        }
          
        PrintWriter out = null;  
        response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码  
        out = response.getWriter();  
        out.print("文件导入成功！");  
        out.flush();  
        out.close();  
    }  
   
	private void packageSignLogCount(List<SignLogVO> signLogList,List<SignLogVO> returnList) {
		Map<String,String> map = new HashMap<String,String>();
		for (SignLogVO signLogVO : signLogList) {
			if(!map.containsKey(signLogVO.getJobNumber())) {
				map.put(signLogVO.getJobNumber(), signLogVO.getSignCountTime());
			}
		}
		if(map!=null && map.size() > 0) {
			SignLogVO sign = null;
			for (String num : map.keySet()) {
				sign = new SignLogVO();
				sign.setJobNumber(num);
				sign.setSignCountTime(map.get(num));
				returnList.add(sign);
			}
		}
	}
}
